package com.wsoft.bpm.component.command;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.wsoft.bpm.mapper.BpmActivitiMapper;
import lombok.AllArgsConstructor;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
import org.activiti.engine.impl.persistence.entity.HistoricActivityInstanceEntityManager;

import java.util.Date;

/**
 * @Author zhonglj
 * @Date 2024/12/5 17:22
 */
@AllArgsConstructor
public class InsertHistoricInfoCommand implements Command<Boolean> {
    private String id;
    private String name;
    private String assignee;
    private Date startTime;
    private String processInstanceId;
    private String processDefinitionId;
    private String executionId;
    private String taskDefinitionKey;

    @Override
    public Boolean execute(CommandContext commandContext) {
        BpmActivitiMapper activitiMapper = SpringUtil.getBean(BpmActivitiMapper.class);
        activitiMapper.updateHiTaskProcInstId(id, processInstanceId, processDefinitionId, executionId, taskDefinitionKey);

        HistoricActivityInstanceEntityManager historicActivityInstanceEntityManager = commandContext.getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
        // 获取ID生成器
        IdGenerator idGenerator = commandContext.getProcessEngineConfiguration().getIdGenerator();
        // 创建一个历史活动实例
        HistoricActivityInstanceEntity historicActivityInstance = historicActivityInstanceEntityManager.create();
        // 设置历史活动实例的属性
        historicActivityInstance.setId(idGenerator.getNextId());
        historicActivityInstance.setProcessInstanceId(processInstanceId);
        historicActivityInstance.setActivityName(name);
        historicActivityInstance.setActivityType("userTask");
        historicActivityInstance.setStartTime(startTime);
        historicActivityInstance.setEndTime(DateUtil.date());
        historicActivityInstance.setDurationInMillis(DateUtil.betweenMs(startTime, historicActivityInstance.getEndTime()));
        historicActivityInstance.setAssignee(assignee);
        historicActivityInstance.setTaskId(id);
        historicActivityInstance.setProcessDefinitionId(processDefinitionId);
        historicActivityInstance.setProcessInstanceId(processInstanceId);
        historicActivityInstance.setExecutionId(executionId);
        historicActivityInstance.setActivityId(taskDefinitionKey);
        // 插入历史活动实例
        historicActivityInstanceEntityManager.insert(historicActivityInstance);

        return true;
    }
}
